package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    private static final String WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties wechatProperties;
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User WXLogin(UserLoginDTO userLoginDTO) {
       String code = userLoginDTO.getCode();//微信端传过来的临时凭证
       String openid = getOpenid(code);//调用微信接口，获取openid
        //判断openid是否为空
        if (openid == null){
            //微信登录失败
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否为新用户，
        User user = userMapper.getByOpenid(openid);
        if (user == null){
            //新用户，自动完成注册
            user = User.builder()
                    .createTime(LocalDateTime.now())
                    .openid(openid)
                    .build();
            userMapper.insert(user);
        }
        //返回用户对象
        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        Map<String,String> map = new HashMap<>();
        map.put("appid",wechatProperties.getAppid());//微信开放平台审核通过的应用APPID
        map.put("secret",wechatProperties.getSecret());//微信开放平台审核通过的应用APPSECRET
        map.put("js_code",code);//微信返回的临时登录凭证code
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WECHAT_LOGIN_URL, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
